﻿using JKFrame;
using Cinemachine;
using UnityEngine;
using Unity.Netcode;

public class PlayerManager : SingletonMono<PlayerManager>
{
    public PlayerClientController localPlayer { get; private set; }

    // 玩家是否可以控制角色，以后可能受到多个方面的影响，目前只和鼠标显示关联
    public bool playerControlEnable { get; private set; }
    //public int UsedWeaponIndex => bagData.usedWeaponIndex;

    private bool requestOpenBagWindow = false;
    //public BagData bagData { get; private set; }
    public void Init()
    {
        PlayerController.SetGetWeaponFunc(GetWeapon);
        EventSystem.AddTypeEventListener<SpawnPlayerEvent>(OnSpawnPlayerEvent);
        EventSystem.AddTypeEventListener<MouseActiveStateChangedEvent>(OnMouseActiveStateChangedEvent);
        NetMessageManager.Instance.RegisterMessageCallback(MessageType.S_C_GetBagData, OnS_C_GetBagData);
        NetMessageManager.Instance.RegisterMessageCallback(MessageType.S_C_BagUpdateItem, OnS_C_UpdateItem);
        NetMessageManager.Instance.RegisterMessageCallback(MessageType.S_C_ShortcutBarUpdateItem, OnS_C_ShortcutBarUpdateItem);
        //NetMessageManager.Instance.RegisterMessageCallback(MessageType.S_C_UpdateCoinCount, OnS_C_UpdateCoinCount);
        Global.Instance.ActiveMouse = false;
        RequestBagData();
    }

    private void OnDestroy()
    {
        EventSystem.RemoveTypeEventListener<SpawnPlayerEvent>(OnSpawnPlayerEvent);
        EventSystem.RemoveTypeEventListener<MouseActiveStateChangedEvent>(OnMouseActiveStateChangedEvent);
        NetMessageManager.Instance.UnRegisterMessageCallback(MessageType.S_C_GetBagData, OnS_C_GetBagData);
        NetMessageManager.Instance.UnRegisterMessageCallback(MessageType.S_C_BagUpdateItem, OnS_C_UpdateItem);
        NetMessageManager.Instance.UnRegisterMessageCallback(MessageType.S_C_ShortcutBarUpdateItem, OnS_C_ShortcutBarUpdateItem);
    }

    private void OnSpawnPlayerEvent(SpawnPlayerEvent arg)
    {
        if (arg.newPlayer.IsOwner)
        {
            InitLocalPlayer((PlayerClientController)arg.newPlayer.sideController);
        }
    }
    private void OnMouseActiveStateChangedEvent(MouseActiveStateChangedEvent arg)
    {
        // 目前只和鼠标是否显示关联
        playerControlEnable = !arg.activeState;
        CameraManager.Instance.SetControlState(playerControlEnable);
        if (localPlayer != null)
        {
            localPlayer.canControl = playerControlEnable;
        }
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //if (!ClientUtility.GetWindowActiveState(out UI_GamePopupWindow gamePopupWindow))
            //{
            //    UISystem.Show<UI_GamePopupWindow>();
            //}
            //else UISystem.Close<UI_GamePopupWindow>();

        }

        if (Input.GetKeyDown(KeyCode.I))
        {
            //if (!ClientUtility.GetWindowActiveState(out UI_BagWindow bagWindow))
            //{
            //    OpenBagWindow();
            //}
            //else UISystem.Close<UI_BagWindow>();
        }
    }

    private void OpenBagWindow()
    {
        requestOpenBagWindow = true;
        RequestBagData();
    }

    private void RequestBagData()
    {
        // 请求网络
        //int dataVersion = bagData == null ? -1 : bagData.dataVersion;
        //NetMessageManager.Instance.SendMessageToServer(MessageType.C_S_GetBagData, new C_S_GetBagData { dataVersion = dataVersion });
        // 等网络消息回发
    }

    private void OnS_C_GetBagData(ulong serverID, INetworkSerializable serializable)
    {
       

    }
    public bool IsLoadingCompleted()
    {
        return localPlayer != null;
    }

    private void InitLocalPlayer(PlayerClientController player)
    {
        localPlayer = player;
        CameraManager.Instance.Init(localPlayer.cameraLooakTarget, localPlayer.cameraFollowTarget);
        localPlayer.canControl = playerControlEnable;
    }

    public void UseItem(int slotIndex)
    {
        C_S_BagUseItem message = new C_S_BagUseItem { bagIndex = slotIndex };
        NetMessageManager.Instance.SendMessageToServer(MessageType.C_S_BagUseItem, message);
    }
    private void OnS_C_UpdateItem(ulong serverID, INetworkSerializable serializable)
    {
        S_C_BagUpdateItem message = (S_C_BagUpdateItem)serializable;
        // 版本一致不需要考虑
        //if (bagData == null || bagData.dataVersion == message.bagDataVersion) return;
        //ItemDataBase itemData = message.newItemData;
        //bagData.itemList[message.itemIndex] = itemData;
        //bagData.dataVersion = message.bagDataVersion;

        //if (message.usedWeapon) // 更新武器
        //{
        //    bagData.usedWeaponIndex = message.itemIndex;
        //}
        //// 如果背包是打开状态则同步给背包
        //if (ClientUtility.GetWindowActiveState(out UI_BagWindow bagWindow))
        //{
        //    bagWindow.UpdateItem(message.itemIndex, itemData);
        //}
        //if (ClientUtility.GetWindowActiveState(out UI_ShortcutBarWindow shortcutBarWindow))
        //{
        //    shortcutBarWindow.UpdateItemByBagIndex(message.itemIndex, itemData);
        //}
        //if (ClientUtility.GetWindowActiveState(out UI_CraftWindow craftWindow))
        //{
        //    craftWindow.UpdateCraftArea();
        //}
    }

    private GameObject GetWeapon(string weapoName)
    {
        GameObject weaponObj = PoolSystem.GetGameObject(weapoName);
        if (weaponObj == null)
        {
            //WeaponConfig weaponConfig = ResSystem.LoadAsset<WeaponConfig>(weapoName);
            //weaponObj = Instantiate(weaponConfig.prefab);
            weaponObj.name = weapoName;
        }
        return weaponObj;
    }

    private void OnS_C_ShortcutBarUpdateItem(ulong serverID, INetworkSerializable serializable)
    {
        //S_C_ShortcutBarUpdateItem message = (S_C_ShortcutBarUpdateItem)serializable;
        //if (bagData.dataVersion == message.bagDataVersion) return;
        //bagData.dataVersion = message.bagDataVersion;
        //// 通知快捷栏
        //if (ClientUtility.GetWindowActiveState(out UI_ShortcutBarWindow shortcutBarWindow))
        //{
        //    shortcutBarWindow.SetItem(message.shortcutBarIndex, message.bagIndex, bagData);
        //}
    }

    //public void OpenShop(string merchatConfigName)
    //{
    //    if (!ClientUtility.GetWindowActiveState<UI_ShopWindow>(out _))
    //    {
    //        UISystem.Show<UI_ShopWindow>().Show(ResSystem.LoadAsset<MerchantConfig>(merchatConfigName));
    //        if (!requestOpenBagWindow && !ClientUtility.GetWindowActiveState(out UI_BagWindow bagWindow))
    //        {
    //            OpenBagWindow();
    //        }
    //    }
    //}

    //public void ShopBuyItem(ItemConfigBase targetItemConfig, int bagIndex)
    //{
    //    // 金币是否足够
    //    if (targetItemConfig.price > bagData.coinCount)
    //    {
    //        UISystem.Show<UI_MessagePopupWindow>().ShowMessageByLocalzationKey(ErrorCode.CoinsInsufficient.ToString(), Color.yellow);
    //        return;
    //    }

    //    // 背包空间检测
    //    ItemDataBase existeItemData = bagData.TryGetItem(targetItemConfig.name, out int existeBagIndex);
    //    ItemDataBase targetSlotItemData = bagData.itemList[bagIndex];

    //    bool check;
    //    // 堆叠物品可以是空位或者是同物品
    //    if (targetItemConfig.GetDefaultItemData() is StackableItemDataBase)
    //    {
    //        check = targetSlotItemData == null || existeItemData != null;
    //        if (existeItemData != null)
    //        {
    //            bagIndex = existeBagIndex;
    //        }
    //    }
    //    // 武器必须在空位
    //    else
    //    {
    //        check = targetSlotItemData == null;
    //    }
    //    if (!check)
    //    {
    //        UISystem.Show<UI_MessagePopupWindow>().ShowMessageByLocalzationKey(ErrorCode.LackOfBagSpace.ToString(), Color.yellow);
    //        return;
    //    }
    //    // 发送网络消息
    //    NetMessageManager.Instance.SendMessageToServer(MessageType.C_S_ShopBuyItem,
    //        new C_S_ShopBuyItem { itemID = targetItemConfig.name, bagIndex = bagIndex });
    //}

    //private void OnS_C_UpdateCoinCount(ulong serverID, INetworkSerializable serializable)
    //{
    //    S_C_UpdateCoinCount message = (S_C_UpdateCoinCount)serializable;
    //    if (bagData.dataVersion == message.bagDataVersion) return;
    //    bagData.dataVersion = message.bagDataVersion;
    //    bagData.coinCount = message.coinCount;
    //    if (ClientUtility.GetWindowActiveState(out UI_BagWindow bagWindow))
    //    {
    //        bagWindow.UpdateCoin(bagData.coinCount);
    //    }

    //}

    public void OpenCraft(string configName)
    {

    }
}
